package com.bzr.emos.wx.Service;

// 导入必要的类和包
import com.bzr.emos.wx.common.util.R;          // 自定义的通用返回结果类
import com.bzr.emos.wx.config.security.LoginDTO; // 登录数据传输对象（包含用户名和密码）
import com.bzr.emos.wx.config.security.MyUserDetails;
import com.bzr.emos.wx.util.JwtUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager; // Spring Security认证管理器
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; // 用户名密码认证令牌
import org.springframework.security.core.Authentication; // 认证信息接口
import org.springframework.security.core.AuthenticationException; // 认证异常基类
import org.springframework.security.core.context.SecurityContextHolder; // 安全上下文持有者
import org.springframework.security.core.userdetails.UserDetailsService; // 用户详情服务接口
import org.springframework.stereotype.Service; // 标识为Spring服务组件


@Service
public class LoginService {
    @Resource
    private AuthenticationManager authenticationManager;    //上一步已实现

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    //验证登录的方法
    public R checkLogin(LoginDTO login, HttpServletResponse response) {
        // 得到用户名和密码参数
        String username = login.getUsername();
        String password = login.getPassword();
        // 封装到一个待认证的authRequest对象中
        UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username,
                password);
        try{
            // 发起认证得到认证后的结果authentication对象
            Authentication authentication = authenticationManager.authenticate(authRequest);
            if (authentication.isAuthenticated()) {
                // 认证成功返回结果(JSON)，应注意authentication对象放入安全上下文供后续过滤器取用(重要)
                SecurityContextHolder.getContext().setAuthentication(authentication);
                Integer subject = ((MyUserDetails) authentication.getPrincipal()).getUser().getId();
                String token = JwtUtils.generateToken((subject.toString()));
                redisTemplate.opsForValue().set(subject.toString(), token);
                // 创建Cookie对象
                Cookie cookie = new Cookie("DlToken", token);
                cookie.setHttpOnly(true);
                cookie.setSecure(true);
                cookie.setPath("/");
                cookie.setMaxAge(1 * 24 * 60 * 60); // 7天
                response.addCookie(cookie);



                return R.ok().put("DlToken", token);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return R.error();
    }
}
